package top.lingchen.blogapi.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import top.lingchen.blogapi.bean.Article;
import top.lingchen.blogapi.mapper.ArticleMapper;

/**
 * @Author 凌宸
 * @create 2021-12-17 下午 2:17
 * @Description
 * @Version 1.0
 */
@Component
public class ThreadService {

    /**
     * 期望此操作在线程池中执行，不会影响原有的主程序
     * @param articleMapper
     * @param article
     */
    @Async("taskExecutor")
    public void updateArctileViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId, article.getId());
        // 保证多线程并发下，线程安全
        updateWrapper.eq(Article::getViewCounts, viewCounts); // 相当于版本号 version
        articleMapper.update(articleUpdate, updateWrapper);
    }
}
